const express = require('express');
const app = express();
var path = require('path');
// 2.解决跨域请求
//  var cors=require('cors'); //在后端处理跨域
var jwt=require('express-jwt');
var token=require('./util/token');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var goodsRouter = require('./routes/goods');
var cartsRouter = require('./routes/carts');
var accountRouter = require('./routes/accounts');
var adminRouter = require('./routes/admin');

// 静态资源托管
app.use(express.static('public'))

// 配置express-jwt的基本验证 对于所有请求，除了路径为/users/login的请求，都会通过express-jwt中间件进行JWT验证。
app.use(jwt.expressjwt({ //这是express-jwt的工厂函数，用于创建一个中间件。
    secret:"haha", //验证JWT的密钥
    algorithms:['HS256'] //这指定了用于JWT签名的算法
}).unless({   //.unless({...}): 这是一个条件排除方法，用于指定中间件不应处理哪些请求。
    path:['/users/login','/users/login2','/users/reg','/goods/goodsByCate','/goods/goodsById','/carts/getCount','/admin/showgoods','/admin/addgoods','/admin/editgoods','/admin/Offshelf','/admin/Onshelf','/admin/showusers','/admin/showtrueorder','/admin/showfalseorder','/admin/ConfirmShipment','/admin/yizhifu','/admin/weizhifu','/admin/userstatistics','/admin/salestatistics','/admin/echone','/admin/echtwo','/admin/echthree']
}))
// 验证token过滤中间件
app.use((req,res,next)=>{
   
    var t=req.headers['authorization'];
    if(t){
        token.getToken(t).then((data)=>{
            req.data=data;
            return next();
        }).catch(err=>{
            return next();
        })
    }else{
        return next();
    }
});
//token验证之后处理中间件
app.use((err,req,res,next)=>{
    if(err.status==401){
        res.send({code:401,message:'token失效了'});
    }else{
        next();
    }
})

app.use((req,res,next)=>{
    console.log(req.url);
    next();
})
// app.use(express.static(path.join(__dirname, 'public')));  当上传的图片文件放后台处理时可保留
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/goods', goodsRouter);
app.use('/carts', cartsRouter);
app.use('/accounts', accountRouter);
app.use('/admin', adminRouter);

module.exports = app;
